package com.sc.nft.admin.consume;

import com.sc.nft.dao.OrderGasDetailDao;
import com.sc.nft.entity.OrderGasDetail;
import com.sc.nft.entity.dto.OrderGasShareDTO;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘国航
 * @desc
 * @since 2024/10/21 15:31
 */
@RocketMQMessageListener(topic = MessageTopic.ORDER_GAS_SHARE + "${spring.profiles.active}", consumerGroup = MessageTopic.ORDER_GAS_SHARE + "${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderGasShareConsumer implements RocketMQListener<OrderGasShareDTO> {

    private final RedissonClient redissonClient;
    private final OrderGasDetailDao orderGasDetailDao;

    @Override
    public void onMessage(OrderGasShareDTO message) {
        String key = RedisKeyEnum.ORDER_GAS_SHARE.getKey() + message.getOrderId() + "_" + message.getOrderNo() + "_" + message.getOrderType();
        RLock lock = redissonClient.getLock(key);
        try {
            if (!lock.tryLock(30, TimeUnit.SECONDS)) {
                throw new GlobalRunTimeException("获取锁失败");
            }
            OrderGasDetail orderGasDetail = orderGasDetailDao.getByOrderIdNoType(message.getOrderId(), message.getOrderNo(), message.getOrderType());
            if (Objects.nonNull(orderGasDetail)) {
                return;
            }
            orderGasDetail = new OrderGasDetail();
            orderGasDetail.setOrderId(message.getOrderId());
            orderGasDetail.setOrderNo(message.getOrderNo());
            orderGasDetail.setOrderType(message.getOrderType());
            orderGasDetail.setGas(message.getGas());
            orderGasDetail.setOrderTime(message.getOrderTime());
            orderGasDetail.setCounted(Boolean.FALSE);
            orderGasDetail.setSettled(Boolean.FALSE);
            orderGasDetail.insert();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
